using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class DeleteInpatientOrderTemplateCommandHandler : IRequestHandler<DeleteInpatientOrderTemplateCommand, bool>
	{
		private readonly IBaseRepository<InpatientOrderTemplate> _repository;

		public DeleteInpatientOrderTemplateCommandHandler(IBaseRepository<InpatientOrderTemplate> repository)
		{
			_repository = repository;
		}

		public async Task<bool> Handle(DeleteInpatientOrderTemplateCommand request, CancellationToken cancellationToken)
		{
			var entity = await _repository.GetModel(x => x.TemplateId == request.TemplateId && !x.IsDeleted);
			if (entity == null)
			{
				throw new Exception("模板不存在");
			}

			entity.IsDeleted = true;
			entity.DeletedAt = DateTime.Now;
			entity.DeletedBy = request.DeletedBy;
			entity.UpdatedAt = DateTime.Now;
			await _repository.UpdateAsync(entity);
			return true;
		}
	}
}
